package tools

import (
	"bytes"
	"net/http"
	"io/ioutil"
	"encoding/json"
	"hub.hddznet.com/app/framework/errs"
	"hub.hddznet.com/uniplatform/framework/logging"
	"io"
	"crypto/tls"
	"strings"
	"time"
)

type HDPostResult struct {
	Code     int         `json:"Code"`
	Message  string      `json:"Message"`
	Response interface{} `json:"Response"`
}

func HDPOST(url string, param interface{}) (*HDPostResult, error) {
	bytesData, err := json.Marshal(param)
	if err != nil {
		return nil, errs.JsonStrfyErr(err)
	}
	reader := bytes.NewReader(bytesData)
	return HDPOST_Proxy(url, reader, nil)
}

func HDPOST_Proxy(url string, param io.Reader, header http.Header) (*HDPostResult, error) {
	respBytes, err := POST_Proxy(url, param, header)
	if err != nil {
		return nil, errs.HttpGetDataErr()
	}
	result := &HDPostResult{}
	err = json.Unmarshal(respBytes, &result)
	if err != nil {
		logging.Error("第三方接口返回数据解析错误", err)
		return nil, errs.ThirdAnalyzeErr(err.Error())
	} else {
		return result, nil
	}
}

func HDGet_Proxy(url string, param io.Reader, header http.Header) (*HDPostResult, error) {
	respBytes, err := GET_Proxy(url, param, header)
	if err != nil {
		return nil, errs.HttpGetDataErr()
	}
	result := &HDPostResult{}
	err = json.Unmarshal(respBytes, &result)
	if err != nil {
		logging.Error("第三方接口返回数据解析错误", err)
		return nil, errs.ThirdAnalyzeErr(err.Error())
	} else {
		return result, nil
	}
}

func POST_Proxy(url string, param io.Reader, header http.Header) ([]byte, error) {
	request, err := http.NewRequest("POST", url, param)
	if header != nil {
		request.Header = header
	}
	if err != nil {
		return nil, errs.HttpRequestCreateErr(err)
	}
	return HttpAction(url, request)
}

func GET_Proxy(url string, param io.Reader, header http.Header) ([]byte, error) {
	request, err := http.NewRequest("GET", url, param)
	if header != nil {
		request.Header = header
	}
	if err != nil {
		return nil, errs.HttpRequestCreateErr(err)
	}
	return HttpAction(url, request)
}

func HttpAction(url string, request *http.Request) ([]byte, error) {
	client := http.Client{}
	if strings.Index(url, "https://") == 0 {
		client.Transport = &http.Transport{
			TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
		}
	}
	client.Timeout = time.Second * 30
	resp, err := client.Do(request)
	if err != nil {
		return nil, errs.HttpResponseParseErr()
	}
	respBytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, errs.HttpGetDataErr()
	}
	return respBytes, nil
}
